package com.it.schoolbookshop_back.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 雪花算法ID生成器
 * Twitter的雪花算法SnowFlake，使用Java语言实现
 */
@Slf4j
@Component
public class SnowflakeIdGenerator {
    /**
     * 起始的时间戳（2025-01-01）
     */
    private final static long START_TIMESTAMP = 1735660800000L;

    /**
     * 每一部分占用的位数
     */
    private final static long SEQUENCE_BIT = 12;  // 序列号占用的位数
    private final static long MACHINE_BIT = 5;    // 机器标识占用的位数
    private final static long DATA_CENTER_BIT = 5;// 数据中心占用的位数

    /**
     * 每一部分的最大值
     */
    private final static long MAX_SEQUENCE = ~(-1L << SEQUENCE_BIT);
    private final static long MAX_MACHINE_NUM = ~(-1L << MACHINE_BIT);
    private final static long MAX_DATA_CENTER_NUM = ~(-1L << DATA_CENTER_BIT);

    /**
     * 每一部分向左的位移
     */
    private final static long MACHINE_LEFT = SEQUENCE_BIT;
    private final static long DATA_CENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
    private final static long TIMESTAMP_LEFT = DATA_CENTER_LEFT + DATA_CENTER_BIT;

    /**
     * 数据中心ID(0~31)
     */
    private long dataCenterId;
    /**
     * 机器ID(0~31)
     */
    private long machineId;
    /**
     * 序列号
     */
    private long sequence = 0L;
    /**
     * 上一次时间戳
     */
    private long lastTimestamp = -1L;

    /**
     * 默认构造函数，使用默认的数据中心ID和机器ID
     */
    public SnowflakeIdGenerator() {
        this(1, 1);
    }

    /**
     * 构造函数
     *
     * @param dataCenterId 数据中心ID (0~31)
     * @param machineId    机器ID (0~31)
     */
    public SnowflakeIdGenerator(long dataCenterId, long machineId) {
        if (dataCenterId > MAX_DATA_CENTER_NUM || dataCenterId < 0) {
            throw new IllegalArgumentException("数据中心ID不能大于" + MAX_DATA_CENTER_NUM + "或小于0");
        }
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("机器ID不能大于" + MAX_MACHINE_NUM + "或小于0");
        }
        this.dataCenterId = dataCenterId;
        this.machineId = machineId;
        log.info("初始化雪花算法ID生成器成功, 数据中心ID: {}, 机器ID: {}", dataCenterId, machineId);
    }

    /**
     * 获取下一个ID
     */
    public synchronized long nextId() {
        long currentTimestamp = getCurrentTimestamp();
        
        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过，抛出异常
        if (currentTimestamp < lastTimestamp) {
            throw new RuntimeException("系统时钟回退，拒绝生成ID");
        }

        // 如果是同一时间生成的，则进行序列号递增
        if (currentTimestamp == lastTimestamp) {
            // 序列号递增
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 序列号已经达到最大值，等待下一个毫秒
            if (sequence == 0L) {
                currentTimestamp = getNextTimestamp(lastTimestamp);
            }
        } else {
            // 时间戳改变，重置序列号
            sequence = 0L;
        }

        // 更新上次生成ID的时间戳
        lastTimestamp = currentTimestamp;

        // 移位并通过或运算拼到一起组成64位的ID
        return ((currentTimestamp - START_TIMESTAMP) << TIMESTAMP_LEFT)
                | (dataCenterId << DATA_CENTER_LEFT)
                | (machineId << MACHINE_LEFT)
                | sequence;
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     */
    private long getNextTimestamp(long lastTimestamp) {
        long timestamp = getCurrentTimestamp();
        while (timestamp <= lastTimestamp) {
            timestamp = getCurrentTimestamp();
        }
        return timestamp;
    }

    /**
     * 获取当前时间戳
     */
    private long getCurrentTimestamp() {
        return System.currentTimeMillis();
    }
} 